/**
 * 
 */
package com.tiduyun.data.exchange.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import com.tiduyun.data.exchange.constant.ExceptionCode;
import com.tiduyun.data.exchange.exception.CodedRuntimeException;

import lombok.extern.slf4j.Slf4j;

/**
 * @author MiniKnife
 *
 */
@RestControllerAdvice
@Slf4j
public class CustomResponseEntityExceptionHandler {

    @ExceptionHandler
    public ResponseEntity<Object> handleException(Exception ex, WebRequest request) {
        Map<String, Object> wrapper = new HashMap<>();
        if (!(ex instanceof CodedRuntimeException)) {
            log.error("unexpect exception: request={}", request, ex);
            wrapper.put("code", ExceptionCode.SYSTEM_ERROR);
            wrapper.put("msg", ex.getMessage());
        } else {
            log.info("coded runtime exception: request={}", request, ex);
            CodedRuntimeException cre = (CodedRuntimeException) ex;
            wrapper.put("code", cre.getCode());
            wrapper.put("msg", cre.getMessage());
        }
        return ResponseEntity.ok(wrapper);
    }

}
